package com.wuchao.xml;

import com.wuchao.entity.Bookstore;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author wuchao66
 * @Date 2023/10/27 15:29
 * @PackageName:com.wuchao.xml
 * @ClassName: T167XML
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
public class T167XML {
    public static void main(String[] args) throws DocumentException, IOException {
        //建立读取器
        SAXReader reader = new SAXReader();
        //把我们对应的xml文件读成文档树
        Document dom = reader.read(new File("D:\\idea-project\\t167ssmbt\\src\\main\\resources\\bookt167.xml"));
        //拿根
        Element gen = dom.getRootElement();
        //加一个根的孩子
        Element man = gen.addElement("铁一样的男银");
       // gen.remove(man);
        man.setAttributeValue("id","6");
        Element man1 = man.addElement("去健身房撕背心的男银");
        Element name = man1.addElement("name");
        name.setText("我是新的孙节点");
        //得到根的孩子s
        Iterator zis = gen.elementIterator();
        List<Bookstore> list=new ArrayList<>();
        //循环遍历孩子节点
        while(zis.hasNext()){
            //得到每一个孩子
            Bookstore bookstore = new Bookstore();
            Element zi = (Element)zis.next();
            System.out.println("孩子的名字"+zi.getName());
            //孩子的属性集合
            List<Attribute> attributes = zi.attributes();
            attributes.forEach(xjj->{
                if(xjj.getValue().equals("2")){
                    xjj.setValue("666");
                }
            });
            attributes.forEach(xjj-> {System.out.println("子节点的属性名"+xjj.getName()
            +"属性值"+xjj.getValue());
                bookstore.book=Integer.parseInt(xjj.getValue()) ;
            });

            //得到根的孩子的孩子s
            Iterator sun = zi.elementIterator();
            while(sun.hasNext()) {
                //得到每一个孩子
                Element sun1 = (Element) sun.next();
                System.out.println("孙子的名字" + sun1.getName()+
                        "孙子的值"+sun1.getStringValue());
                if(sun1.getName().equals("name")){
                    bookstore.name=sun1.getStringValue();
                }
            }
            System.out.println("---------------------");
            list.add(bookstore);
        }
        list.forEach(System.out::println);
        //打印出新的xml
        XMLWriter writer = new XMLWriter(
                new FileWriter("D:\\idea-project\\t167ssmbt\\src\\main\\resources\\bookt169.xml"));
        writer.write(gen);
        writer.close();
        System.out.println("输出完毕");

    }
}
